package training.project.app.web;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import training.project.app.domain.Flight;
import training.project.app.domain.UserAccount;
import training.project.app.service.FlightClientService;
import training.project.app.service.FlightService;
import training.project.app.service.UtilService;

@Controller
@RequestMapping("/profile/flights")
public class FlightAjaxController
	{
		@Autowired
		private FlightService flightService;
		@Autowired
		private FlightClientService flightClientService;
		@Autowired
		private UtilService utilService;
		@Autowired
		private SessionFactory sessionFactory;

		@PreAuthorize("isFullyAuthenticated() and hasAnyRole('ROLE_ADMIN','ROLE_USER')")
		@RequestMapping(value = "/ajax", method = { RequestMethod.POST })
		@ResponseBody
		public List<Flight> findFlights(@RequestBody String request,
				HttpSession session, Model model)
			{
				String[] parameters = request.split("&");
				String startPlace = utilService.GetParam(parameters, 1, 11);
				String endPlace = utilService.GetParam(parameters, 0, 9);
				Boolean vip = utilService.IsTrue(utilService.GetParam(
						parameters, 2, 4));
				Boolean baggage = utilService.IsTrue(utilService.GetParam(
						parameters, 3, 8));
				List<Flight> Foundedflights = flightService.findFlights(
						startPlace, endPlace);
				UserAccount user = (UserAccount)session.getAttribute("user");
				Foundedflights = flightService.DoNotShowBookedAndPurchaseFlights(Foundedflights, user.getUserId());
				Foundedflights = flightService.increasePriceCuzVipAndBaggage(
						Foundedflights, vip, baggage);
				return Foundedflights;
			}

		/*@PreAuthorize("isFullyAuthenticated() and hasAnyRole('ROLE_ADMIN','ROLE_USER')")
		@RequestMapping(value = "book/{id}/ajax", method = { RequestMethod.POST })
		@ResponseBody
		public void bookFlights(@RequestBody String request, Integer id,
				Boolean vip, Boolean baggage, HttpSession session, Model model)
			{
				Object userObject = session.getAttribute("user");
				UserAccount user = (UserAccount) userObject;
				FlightClient newFlightClient = new FlightClient(0, user,
						flightService.getFlightById(id), vip, baggage, 50F);
				flightClientService.saveFlightClient(newFlightClient);
			}*/
	}
